package com.sophialex.health.record.common.ktable;

import com.sophialex.health.system.frame.util.RefMethod;
import com.sophialex.health.system.frame.widgets.dbTable.JoinOutFieldDescription;

public class KTableUtil {

	public final static String DOT_FLAG = ".";

	public final static String A_FlAG = "@";

	public static Object getTableColumnText(Object element,
			KTableBaseModel model, int columnIndex) {
		if (element == null)
			return "";
		Object objValue = null;
		String colField = null;
		String property = (String) model.getColumnProperties()[columnIndex];
		if (property.trim().length() == 0)
			return "";
		int dSite = property.indexOf(DOT_FLAG);

		if (dSite < 0) {
			int aSite = -1;
			JoinOutFieldDescription joinOutValue = null;
			for (int i = 0; i < model.getJoinOutList().size(); i++) {
				aSite = model.getJoinOutList().get(i).getByField().indexOf(
						property);
				if (aSite == 0) {
					joinOutValue = model.getJoinOutList().get(i);
					break;
				}
			}

			if (aSite < 0) {
				colField = property;
				try {
					objValue = RefMethod.invokeGetMethod(element, RefMethod
							.gainGetMethod(colField));
				} catch (Exception e) {
				}
				return objValue == null ? "" : objValue;
			} else {

				if (joinOutValue != null) {
					Object joinElement = "";
					joinElement = RefMethod.invokeGetMethod(element, RefMethod
							.gainGetMethod(joinOutValue.getByField()));
					try {
						return joinOutValue.getJoin().getFieldValue(element,
								property, joinElement);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}
			}
		} else {
			if (colField == null)
				colField = property;
			dSite = colField.indexOf(DOT_FLAG);
			String joinEntity;
			Object joinElement = element;
			while (dSite > -1) {
				joinEntity = colField.substring(0, dSite);
				colField = colField.substring(dSite + 1);
				joinElement = RefMethod.invokeGetMethod(element, RefMethod
						.gainGetMethod(joinEntity));
				if (joinElement == null)
					break;
				dSite = colField.indexOf(DOT_FLAG);
			}
			if (joinElement != null) {
				objValue = RefMethod.invokeGetMethod(joinElement, RefMethod
						.gainGetMethod(colField));
				return objValue;
			} else
				return "";

		}

		return "";
	}
}
